package cn.edu.zafu.bigdata.lmr;

import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClockServer {
    public static void main(String[] args) {
        try {
            // 创建服务端的DatagramSocket，监听端口号1234
            DatagramSocket serverSocket = new DatagramSocket(1234);
            System.out.println("Clock server is running...");

            // 缓冲区用于存储传入的数据包内容
            byte[] receiveBuffer = new byte[1024];
            byte[] sendBuffer = new byte[1024];

            // 无限循环，等待客户端的请求
            while (true) {
                // 创建DatagramPacket对象，用于接收客户端的请求
                DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);
                serverSocket.receive(receivePacket);

                // 获取客户端地址和端口
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                // 获取当前时间
                String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

                // 将时间字符串转换为字节
                sendBuffer = currentTime.getBytes();

                // 创建DatagramPacket对象，用于发送时间给客户端
                DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, clientAddress, clientPort);
                serverSocket.send(sendPacket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
